<?php
/**
 * | ---------------------------------------------------------------------------------------------------
 * | Author：johnxu <fsyzxz@163.com>.
 * | ---------------------------------------------------------------------------------------------------
 * | Home: https://www.johnxu.net.
 * | ---------------------------------------------------------------------------------------------------
 * | Data: 2018/12/31
 * | ---------------------------------------------------------------------------------------------------
 * | Desc: 异步mysql操作
 * | ---------------------------------------------------------------------------------------------------
 */

class Mysql
{
    /**
     * @var \Swoole\MySQL
     */
    private $db;

    private $config
        = array(
            'host'     => '127.0.0.1',
            'user'     => 'root',
            'port'     => 3306,
            'password' => '123',
            'database' => 'test',
            'charset'  => 'utf8',
            'timeout'  => 2
        );

    public function __construct()
    {
        $this->db = new \Swoole\MySQL();
        $this->db->connect( $this->config, function ( \Swoole\MySQL $db, $r ) {
            if ( $r === false )
            {
                var_dump( $db->connect_errno, $db->connect_error );
                die();
            }
            $sql = "show tables";
            $db->query( $sql, function ( \Swoole\MySQL $db, $r ) {
                if ( $r === false )
                {
                    var_dump( $db->error, $db->errno );
                }
                elseif ( $r === true )
                {
                    var_dump( $db->affected_rows, $db->insert_id );
                }

                var_dump( $r );
                $db->close();
            } );
        } );
    }
}


new Mysql();
